﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ProduceBasicData.Api.Application.Command.RBAC.User;
using ProduceBasicData.Domain.RBAC;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using ProduceBasicData.Api.Services;

namespace ProduceBasicData.Api.Application.Handler.RBAC.User
{
    /// <summary>
    /// 用户录入处理类
    /// </summary>
    public class CreateUserHandler : IRequestHandler<CreateUserCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<UserModel> _userRepository;
        private readonly IMapper _mapper;
        private readonly ICodeRuleService codeRuleService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository"></param>
        /// <param name="mapper"></param>
        public CreateUserHandler(IBaseRespository<UserModel> userRepository, IMapper mapper,
            ICodeRuleService codeRuleService)
        {
            _userRepository = userRepository;
            _mapper = mapper;
            this.codeRuleService = codeRuleService;
        }
        /// <summary>
        /// 处理用户录入请求
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                //将命令转换为领域模型
                var user = _mapper.Map<UserModel>(request);
                //判断用户是否存在
                var userExist = await _userRepository.GetAll().AnyAsync(x => x.UserName == user.UserName);
                if (userExist != false)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "用户已存在"
                    };
                }
                //加密密码md5
                user.UserPwd = MD5HashHelper.Encrypt(user.UserPwd);

                //编码
                if (string.IsNullOrEmpty(user.UserCode))
                {
                    var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.RBAC.UserModel");
                    if (!string.IsNullOrEmpty(code))
                    {
                        user.UserCode = code;
                    }
                    else
                    {
                        user.UserCode = $"YH{DateTime.Now:yyyyMMddHHmmss}";
                    }
                }

                //保存用户
                var result = await _userRepository.AddAsync(user);
                if (result > 0)
                {
                    return new ApiResult<int>
                    {
                        Data = result,
                        Code = ApiEnum.Success,
                        Msg = "用户录入成功"
                    };
                }
                else
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "用户信息录入失败"
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = ex.Message
                };
            }
        }
    }
}
